package com.ll.gulimall.order.web;

import com.ll.gulimall.order.service.OrderService;
import com.ll.gulimall.order.vo.OrderConfirmVo;
import com.ll.gulimall.order.vo.OrderSubmitResponseVo;
import com.ll.gulimall.order.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {


    @Autowired
    OrderService orderService;

    /**
     * 结算购物车
     *
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("confirmVo", confirmVo);
        return "confirm";
    }

    /**
     * 提交订单
     *
     * @param orderSubmitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        //去服务器验证token 创建订单 、验价、锁库存
        try {
            OrderSubmitResponseVo orderSubmitResponseVo = orderService.submitOrder(orderSubmitVo);
            //下单成功去支付页面
            if (orderSubmitResponseVo.getCode() == 0) {
                //成功
                model.addAttribute("info", orderSubmitResponseVo);
                return "pay";
            } else {
                //失败
                String msg = "下单失败：";
                switch (orderSubmitResponseVo.getCode()) {
                    case 1:
                        msg += "订单超时，请重新提交！";
                        break;
                    case 2:
                        msg += "订单价格发生变化，请确认后提交！";
                        break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }

        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("msg", "下单失败:服务器内部异常！"+e.getMessage());
            return "redirect:http://order.gulimall.com/toTrade";
        }



    }
}
